package org.cn.hj.basic.common;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.github.pagehelper.PageInfo;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeanUtils;

import java.io.Serializable;
import java.util.concurrent.ConcurrentHashMap;

@Data
@NoArgsConstructor
public class ResultJson implements Serializable {

    private static final long serialVersionUID = 1L;

    private int code = 200;

    private Object data;

    private String msg = "成功啦";

    public ResultJson(Integer code) {
        this.code = code;
    }

    public ResultJson(Object data) {
        this.data = data;
    }

    public ResultJson(int code, Object data) {
        this.code = code;
        this.data = data;
    }

    public ResultJson(int code, Object data, String msg) {
        this.code = code;
        this.data = data;
        this.msg = msg;
    }

    public ResultJson(Object data, String msg) {
        this.data = data;
        this.msg = msg;
    }

    public static ResultJson success(){
        return new ResultJson();
    }

    public static ResultJson success(Object data){
        return new ResultJson(convert(data));
    }

    public static ResultJson success(Object data,String msg){
        return new ResultJson(convert(data),msg);
    }

    public static ResultJson fail(){
        return new ResultJson(500,"失败啦");
    }

    public static ResultJson fail(String msg){
        return new ResultJson(500,"失败啦",msg);
    }

    @Override
    public String toString() {
        return JSONObject.toJSONString(this, SerializerFeature.WriteEnumUsingToString);
    }


    public static Object convert(Object data){
        if (data instanceof PageInfo){
            PageInfo pageInfo = (PageInfo) data;
            LzPage lzPage = new LzPage();
            lzPage.setSize((long) pageInfo.getSize());
            lzPage.setTotal(pageInfo.getTotal());
            lzPage.setPages((long) pageInfo.getPages());
            lzPage.setCurrent((long) pageInfo.getPageNum());
//            BeanUtils.copyProperties(pageInfo,lzPage);
            ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();
            map.put("lzPage",lzPage);
            map.put("records",pageInfo.getList());
            data = map;
        }
        return data;
    }
}
